package com.yun.newBlog.blog.controller;

import com.yun.newBlog.blog.dao.blog.UserMapper;
import com.yun.newBlog.blog.user.JdbcUserDetailsService;
import com.yun.newBlog.blog.user.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SocialUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
public class SignUpController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @Autowired
    private JdbcUserDetailsService jdbcUserDetailsService;

    @RequestMapping("/signup")
    public void signUp(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        if(connection != null) {
            String nickName = connection.getDisplayName(); // 昵称
            String imageUrl = connection.getImageUrl(); // 头像url

            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode("123456");

            UserDetails userDetails = jdbcUserDetailsService.loadUserByUsername(nickName);
            if(userDetails == null){
                jdbcUserDetailsService.createUser(nickName, password, "anonymousUser");
            }

            // 插入用户到userconnection表中
            providerSignInUtils.doPostSignUp(nickName, new ServletWebRequest(request));

            // 重定向到首页
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            response.sendRedirect("http://www.yubuyun.com/mainPage?nickName="+nickName+"&avatar="+imageUrl);
        }
    }
}
